<?php
/* --------------------------------------------------------------
   OrderTrackingLinkService.php 2023-10-18
   Gambio GmbH
   http://www.gambio.de
   Copyright (c) 2023 Gambio GmbH
   Released under the GNU General Public License (Version 2)
   [http://www.gnu.org/licenses/gpl-2.0.html]
   --------------------------------------------------------------
*/

declare(strict_types=1);

namespace GXModules\Gambio\Afterbuy\OrderTracking\App;

use GXModules\Gambio\Afterbuy\AfterbuyCommon\Model\OrderId;
use GXModules\Gambio\Afterbuy\OrderTracking\App\Data\AfterbuyOrderTrackingRepository;
use GXModules\Gambio\Afterbuy\OrderTracking\Exceptions\SyncTrackingLinksFailedException;
use GXModules\Gambio\Afterbuy\OrderTracking\Model\AfterbuyOrderTrackingCodes;
use GXModules\Gambio\Afterbuy\OrderTracking\Service\AfterbuyOrderTrackingLinkService;

/**
 * Class OrderTrackingLinkService
 *
 * @package GXModules\Gambio\Afterbuy\OrderTracking\App
 */
class OrderTrackingLinkService implements AfterbuyOrderTrackingLinkService
{
    /**
     * @var AfterbuyOrderTrackingRepository
     */
    private AfterbuyOrderTrackingRepository $repository;
    
    
    /**
     * OrderTrackingLinkService constructor.
     *
     * @param AfterbuyOrderTrackingRepository $repository
     */
    public function __construct(AfterbuyOrderTrackingRepository $repository)
    {
        $this->repository = $repository;
    }
    
    
    /**
     * @inheritDoc
     */
    public function syncTrackingLinks(string $lastTrackingSyncTime): void
    {
        $trackingCodes = $this->repository->getTrackingCodes($lastTrackingSyncTime);
        $this->syncTrackingCodesFromAfterbuy($trackingCodes);
    }
    
    
    /**
     * @inheritDoc
     */
    public function syncTrackingLinksByOrderId(OrderId $orderId): void
    {
        $trackingCodes = $this->repository->findTrackingCodesByOrderId($orderId);
        if ($trackingCodes) {
            $this->syncTrackingCodesFromAfterbuy($trackingCodes);
        }
    }
    
    
    /**
     * Synchronizes tracking codes generated by Afterbuy orders with the shop system.
     *
     * @throws SyncTrackingLinksFailedException
     */
    private function syncTrackingCodesFromAfterbuy(AfterbuyOrderTrackingCodes $trackingCodes): void
    {
        foreach ($trackingCodes as $trackingCode) {
            if (!$this->repository->orderExists($trackingCode)) {
                continue;
            }
            
            $this->repository->saveTrackingCode($trackingCode);
        }
    }
}